package jjn.round2;

/**
 * @author Jiang Jining
 * @since 2023-06-18 21:13
 */
public class LeetCode1254_ClosedIsland {
    public int closedIsland(int[][] grid) {
        int height = grid.length;
        int width = grid[0].length;
        int result = 0;
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (grid[i][j] == 0 && dfs(grid, i, j)) {
                    result++;
                }
            }
        }
        return result;
    }
    
    private boolean dfs(int[][] grid, int i, int j) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) {
            return false;
        }
        if (grid[i][j] != 0) {
            return true;
        }
        grid[i][j] = 1;
        boolean upper = dfs(grid, i + 1, j);
        boolean lower = dfs(grid, i - 1, j);
        boolean left = dfs(grid, i, j + 1);
        boolean right = dfs(grid, i, j - 1);
        return upper && lower && left && right;
    }
}
